﻿using Newtonsoft.Json;

namespace JsonTest
{
    public static class JsonDictConverter
    {
        public static JsonDictConverter<TKey, TValue> Gen<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            return new JsonDictConverter<TKey, TValue>();
        }

        public static KeyValuePairShell<TKey, TValue> GenKeyValuePairShell<TKey, TValue>(KeyValuePair<TKey, TValue> item)
        {
            return new KeyValuePairShell<TKey, TValue>(item.Key, item.Value);
        }
    }

    public class JsonDictConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
    {
        public override Dictionary<TKey, TValue>? ReadJson(JsonReader reader, Type objectType, Dictionary<TKey, TValue>? existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var s = (string)reader.Value;
            var c = serializer.Deserialize(reader, typeof(List<KeyValuePairShell<TKey, TValue>>)) as List<KeyValuePairShell<TKey, TValue>>;

            var dictionary = new Dictionary<TKey, TValue>();
            foreach (var kv in c)
            {
                dictionary.Add(kv.Key, kv.Value);
            }
            return dictionary;
        }

        public override void WriteJson(JsonWriter writer, Dictionary<TKey, TValue>? value, JsonSerializer serializer)
        {
            var c = value.Select(kvp => new KeyValuePairShell<TKey, TValue>(kvp.Key, kvp.Value)).ToList();
            serializer.Serialize(writer, c);
        }
    }

    public class KeyValuePairShell<TKey, TValue>
    {
        public KeyValuePairShell(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public TKey Key { get; set; }
        public TValue Value { get; set; }
    }
}
